package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.QueryPageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass =CheckGroupService.class )
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupMapper checkGroupMapper;

    @Override
    public List<CheckItem> findCheckItems() {
       return checkGroupMapper.findCheckItems();
    }

    @Override
    public void addCheckGroup(CheckGroup checkGroup) {
        checkGroupMapper.addCheckGroup(checkGroup);
        ArrayList<Map> maps = new ArrayList<>();
        for (Integer checkitemId : checkGroup.getCheckitemIds()) {
            Map<String, Integer> map = new HashMap<>();
            map.put("checkGroupId", checkGroup.getId());
            map.put("checkitemId", checkitemId);
            maps.add(map);
        }
        checkGroupMapper.addCheckGroupAndCheckItem(maps);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        checkGroupMapper.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public CheckGroup findCheckGroupById(int id) {
        return checkGroupMapper.findCheckGroupById(id);
    }

    @Override
    public List<Integer> findCheckItemIds(int id) {
        return checkGroupMapper.findCheckItemIds(id);
    }

    @Override

    public List<CheckGroup> findAll() {
        return checkGroupMapper.findAll();
    }


    public void editCheckGroup(CheckGroup checkGroup) {
        checkGroupMapper.editCheckGroup(checkGroup);
        checkGroupMapper.deleteGroupAndItem(checkGroup.getId());

        ArrayList<Map> maps = new ArrayList<>();
        for (Integer checkitemId : checkGroup.getCheckitemIds()) {
            Map<String, Integer> map = new HashMap<>();
            map.put("checkGroupId", checkGroup.getId());
            map.put("checkitemId", checkitemId);
            maps.add(map);
        }
        checkGroupMapper.addCheckGroupAndCheckItem(maps);
    }

    @Override
    public void deleteById(int id){
        checkGroupMapper.deleteGroupAndItem(id);
        checkGroupMapper.deleteById(id);
    }

}
